package com.aibank.controller;

import com.aibank.entity.Recharge;
import com.aibank.entity.RequestEnity;
import com.aibank.entity.User;
import com.aibank.service.UserService;
import com.aibank.utils.RSAUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 百信银行贷服务器
 */
@Controller
@RequestMapping("/lanmaotech")
public class GatewayController {

    @Value("${key.privateKey}")
    private String privateKey;

    @Value("${key.publicKey}")
    private String publicKey;

    @Autowired
    private UserService userService;

    @PostMapping("/gateway")
    public String gateway(RequestEnity requestEnity, HttpServletRequest request) throws Exception {
        String url = null;
        //校验签名
        String userSign = requestEnity.getSign();
        String subData = RSAUtils.decrypt(userSign, privateKey);
        if(!requestEnity.getReqData().substring(0,100).equals(subData)){
            request.setAttribute("msg","[30003]验证签名失败");
            return "error";
        }

        if(requestEnity.getServiceName()==null || requestEnity.getServiceName().trim().equals("")){
            request.setAttribute("msg","[30001]接口名称不能为空");
            return "error";
        }

        String platformNo = requestEnity.getPlatformNo();
        request.setAttribute("platformNo",platformNo);
        String reqData = requestEnity.getReqData();
        Map map = JSONObject.parseObject(reqData);

        if(requestEnity.getServiceName().equals("PERSONAL_REGISTER_EXPAND")){
            //个人绑卡注册
            String platformUserNo = (String) map.get("platformUserNo");
            String userRole = (String) map.get("userRole");
            String redirectUrl = (String) map.get("redirectUrl");
            String requestNo = (String) map.get("requestNo");
            request.setAttribute("platformUserNo",platformUserNo);
            request.setAttribute("userRole",userRole);
            request.setAttribute("redirectUrl",redirectUrl);
            request.setAttribute("requestNo",requestNo);
            url = "personRegister";
        }
        // 充值接口
        if(requestEnity.getServiceName().equals("RECHARGE")){
            String platformUserNo = (String) map.get("platformUserNo");
            String userRole = (String) map.get("userRole");
            String redirectUrl = (String) map.get("redirectUrl");
            String requestNo = (String) map.get("requestNo");
            request.setAttribute("platformUserNo",platformUserNo);
            request.setAttribute("userRole",userRole);
            request.setAttribute("redirectUrl",redirectUrl);
            request.setAttribute("requestNo",requestNo);
            url = "recharge";
        }
        if(requestEnity.getServiceName().equals("ENTERPRISE_REGISTER")){
            //企业绑卡注册


            url = "enterpriseRegister";
        }

        if(url==null){
            request.setAttribute("msg","[30002]接口名称不存在");
            return "error";
        }
        System.out.println(url);
        request.setAttribute("msg","success");
        return url;
    }

    // 充值，提交表单后过来
    @PostMapping("/Recharge")
    public String Recharge(Recharge Recharge) throws Exception {
        userService.Recharge(Recharge);

        // 按接口封装需要返回的数据（处理返回的参数）
        Map result = new HashMap();
        result.put("requestNo",Recharge.getRequestNo());// 流水号
        result.put("code",0);
        result.put("status","SUCCESS");
        result.put("rechargeStatus","SUCCESS");
        result.put("platformUserNo",Recharge.getPlatformUserNo());
        result.put("amount",Recharge.getCount());
        result.put("commission",Recharge.getCommission());
        result.put("payCompany",Recharge.getPayCompany());
        result.put("rechargeWay",Recharge.getRechargeWay());
        result.put("bankcode",Recharge.getBankcode());
        //......
        String respData = JSONObject.toJSONString(result);// 把实体（对象）转成json字符串

        //按统一格式返回
        Map<String,String> respMap = new HashMap();
        respMap.put("serviceName","RECHARGE");
        respMap.put("platformNo",Recharge.getPlatformNo());
        respMap.put("userDevice","MOBILE");
        respMap.put("responseType","CALLBACK");
        respMap.put("keySerial","1");
        respMap.put("respData",respData);
        String subData = respData.length()>100?respData.substring(0,100):respData;
        respMap.put("sign",RSAUtils.encrypt(subData,publicKey));

        //   http://localhost:5000/resultPersonRegister
        String url = Recharge.getRedirectUrl()+"?";
        String params = "";

        Iterator iterator = respMap.keySet().iterator();
        while (iterator.hasNext()){
            String key = (String) iterator.next();
            String value = respMap.get(key);

            if(key.equals("respData")){
                value = URLEncoder.encode(value,"UTF-8");
            }
            params += "&"+ key+"="+value;
        }
        params = params.substring(1);
        url += params;
        // http://localhost:5000/resultPersonRegister?platformNo=202107270001&responseType=CALLBACK&sign=K/SSf5M/Rdj/G0k3kH2sYJ0acL0Aopj1LRvWooZOMs7lwc/apip7bg+bwmTHboMY/mAu1/HpslcFsmerJIyCfpgwCc3YlirwdOr+vyNIBEJRizN068aROg1PrNgD9fLjNhOgXxhv3CszTbyZZRs9epS8ENiB10yI6FC7qeL9Wtc=&keySerial=1&respData=%7B%22code%22%3A0%2C%22requestNo%22%3A%22d4025626-596f-4995-a91e-5feec9fd001d%22%7D&userDevice=MOBILE&serviceName=PERSONAL_REGISTER_EXPAND
        System.out.println(url);

        // platformNo=202107270001&responseType=CALLBACK&sign=K/SSf5M/Rdj/G0k3kH2sYJ0acL0Aopj1LRvWooZOMs7lwc/apip7bg+bwmTHboMY/mAu1/HpslcFsmerJIyCfpgwCc3YlirwdOr+vyNIBEJRizN068aROg1PrNgD9fLjNhOgXxhv3CszTbyZZRs9epS8ENiB10yI6FC7qeL9Wtc=&keySerial=1&respData=%7B%22code%22%3A0%2C%22requestNo%22%3A%22d4025626-596f-4995-a91e-5feec9fd001d%22%7D&userDevice=MOBILE&serviceName=PERSONAL_REGISTER_EXPAND
        String finalParams = params;
        // 多线程
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String notifyUrl = "http://localhost:5001/notifyResult?"+ finalParams;
                HttpClient httpClient = HttpClients.createDefault();
                HttpGet get = new HttpGet(notifyUrl);
                String result = null;
                try {
                    HttpResponse response = httpClient.execute(get);
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(result);
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();


        return "redirect:"+url;
    }

    // 开户
    @PostMapping("/personRegister")
    public String personRegister(User user) throws Exception {
        userService.personRegister(user);

        // 按接口封装需要返回的数据（处理返回的参数）
        Map result = new HashMap();
        result.put("requestNo",user.getRequestNo());
        result.put("code",0);
        //......
        String respData = JSONObject.toJSONString(result);

        //按统一格式返回
        Map<String,String> respMap = new HashMap();
        respMap.put("serviceName","PERSONAL_REGISTER_EXPAND");
        respMap.put("platformNo",user.getPlatformNo());
        respMap.put("userDevice","MOBILE");
        respMap.put("responseType","CALLBACK");
        respMap.put("keySerial","1");
        respMap.put("respData",respData);
        String subData = respData.length()>100?respData.substring(0,100):respData;
        respMap.put("sign",RSAUtils.encrypt(subData,publicKey));

        //   http://localhost:5000/resultPersonRegister
        String url = user.getRedirectUrl()+"?";
        String params = "";

        Iterator iterator = respMap.keySet().iterator();
        while (iterator.hasNext()){
            String key = (String) iterator.next();
            String value = respMap.get(key);

            if(key.equals("respData")){
                value = URLEncoder.encode(value,"UTF-8");
            }
            params += "&"+ key+"="+value;
        }
        params = params.substring(1);
        url += params;
        // http://localhost:5000/resultPersonRegister?platformNo=202107270001&responseType=CALLBACK&sign=K/SSf5M/Rdj/G0k3kH2sYJ0acL0Aopj1LRvWooZOMs7lwc/apip7bg+bwmTHboMY/mAu1/HpslcFsmerJIyCfpgwCc3YlirwdOr+vyNIBEJRizN068aROg1PrNgD9fLjNhOgXxhv3CszTbyZZRs9epS8ENiB10yI6FC7qeL9Wtc=&keySerial=1&respData=%7B%22code%22%3A0%2C%22requestNo%22%3A%22d4025626-596f-4995-a91e-5feec9fd001d%22%7D&userDevice=MOBILE&serviceName=PERSONAL_REGISTER_EXPAND
        System.out.println(url);

        // platformNo=202107270001&responseType=CALLBACK&sign=K/SSf5M/Rdj/G0k3kH2sYJ0acL0Aopj1LRvWooZOMs7lwc/apip7bg+bwmTHboMY/mAu1/HpslcFsmerJIyCfpgwCc3YlirwdOr+vyNIBEJRizN068aROg1PrNgD9fLjNhOgXxhv3CszTbyZZRs9epS8ENiB10yI6FC7qeL9Wtc=&keySerial=1&respData=%7B%22code%22%3A0%2C%22requestNo%22%3A%22d4025626-596f-4995-a91e-5feec9fd001d%22%7D&userDevice=MOBILE&serviceName=PERSONAL_REGISTER_EXPAND
        String finalParams = params;
        // 多线程
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                String notifyUrl = "http://localhost:5001/notifyResult?"+ finalParams;
                HttpClient httpClient = HttpClients.createDefault();
                HttpGet get = new HttpGet(notifyUrl);
                String result = null;
                try {
                    HttpResponse response = httpClient.execute(get);
                    result = EntityUtils.toString(response.getEntity(), "UTF-8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(result);
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();


        return "redirect:"+url;
    }

}
